<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="参数名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入参数名称"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="参数值" prop="value">
        <el-input
          v-model="queryParams.value"
          placeholder="请输入参数值"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="参数类型" prop="type">
        <el-select
          clearable=""
          v-model="queryParams.type"
          filterable
          placeholder="请选择类型"
        >
          <el-option
            ref="type"
            v-for="item in typeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="告警等级" prop="alarmLevel">
        <el-input
          v-model="queryParams.alarmLevel"
          placeholder="请输入告警等级"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="心跳id" prop="heartbeatId">
                <el-input v-model="queryParams.heartbeatId" placeholder="请输入心跳id" clearable filterable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
      <el-form-item label="参数合法值" prop="heartbeat">
        <el-input
          v-model="queryParams.legalValue"
          placeholder="请输入参数合法值"
          clearable
          filterable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="是否发送通知" prop="isSend">
        <el-select
          clearable=""
          v-model="queryParams.isSend"
          filterable
          placeholder="请选择"
        >
          <el-option
            ref="isSend"
            v-for="item in isSendList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="搜索值" prop="searchValue">
                <el-input v-model="queryParams.searchValue" placeholder="请输入搜索值" clearable filterable
                    @keyup.enter.native="handleQuery" />
            </el-form-item> -->
      <el-form-item label="状态" prop="status">
        <el-select
          clearable=""
          v-model="queryParams.status"
          filterable
          placeholder="请选择"
        >
          <el-option
            v-for="item in statusList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['genius::platform-device-heartbeat:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['genius::platform-device-heartbeat:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['genius::platform-device-heartbeat:removed']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['genius::platform-device-heartbeat:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="heartBeatDetailLsit"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="参数名称" align="center" prop="name" />
      <el-table-column label="参数值" align="center" prop="value" />
      <el-table-column label="参数类型" align="center" prop="type">
        <template slot-scope="scope">
          <div v-if="scope.row.type == 1">int</div>
          <div v-if="scope.row.type == 2">double</div>
          <div v-if="scope.row.type == 3">boolean</div>
          <div v-if="scope.row.type == 4">string</div>
        </template>
      </el-table-column>
      <el-table-column label="告警等级" align="center" prop="alarmLevel" />
      <el-table-column label="参数合法值" align="center" prop="legalValue" />
      <el-table-column label="是否需要发送通知" align="center" prop="isSend">
        <template slot-scope="scope">
          <div v-if="scope.row.isSend == 1">需要</div>
          <div v-if="scope.row.isSend == 0">不需要</div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            active-value="0"
            inactive-value="1"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['genius::platform-device-heartbeat:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['genius::platform-device-heartbeat:removed']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加心跳对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
    >
      <el-table
        v-loading="poolLoading"
        :data="PlatformDeviceHeartbeatPoolList"
        @selection-change="poolHandleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="id" align="center" prop="id" />
        <el-table-column label="参数名称" align="center" prop="name" />
        <el-table-column label="参数类型" align="center" prop="type">
          <template slot-scope="scope">
            <div v-if="scope.row.type == 1">int</div>
            <div v-if="scope.row.type == 2">double</div>
            <div v-if="scope.row.type == 3">boolean</div>
            <div v-if="scope.row.type == 4">string</div>
          </template>
        </el-table-column>
        <el-table-column label="参数值" align="center" prop="value" />
        <el-table-column label="参数合法值" align="center" prop="legalValue" />
        <el-table-column label="功能分类" align="center" prop="functionType">
          <template slot-scope="scope">
            <div v-if="scope.row.functionType == 1">专用类型</div>
            <div v-if="scope.row.functionType == 0">通用类型</div>
          </template>
        </el-table-column>
        <el-table-column label="告警等级" align="center" prop="alarmLevel" />
        <el-table-column label="是否需要发送通知" align="center" prop="isSend">
          <template slot-scope="scope">
            <div v-if="scope.row.isSend == 1">需要</div>
            <div v-if="scope.row.isSend == 0">不需要</div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template slot-scope="scope">
            <div v-if="scope.row.status == 1">停用</div>
            <div v-if="scope.row.status == 0">正常</div>
          </template>
        </el-table-column>

        <el-table-column label="备注" align="center" prop="remark" />
      </el-table>

      <pagination
        v-show="poolTotal > 0"
        :total="poolTotal"
        :page.sync="poolqueryParams.pageNum"
        :limit.sync="poolqueryParams.pageSize"
        @pagination="getpoolList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 修改心跳详情 -->
    <!-- 添加或修改心跳对话框 -->
    <el-dialog
      :title="editTitle"
      :visible.sync="editOpen"
      width="500px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="参数名称" prop="name">
          <el-input
            v-model="form.name"
            placeholder="请输入参数名称"
            clearable
            filterable
          />
        </el-form-item>

        <el-form-item label="参数值（不能重复）" prop="value">
          <el-input
            v-model="form.value"
            placeholder="请输入参数值"
            clearable
            filterable
          />
        </el-form-item>

        <el-form-item label="参数类型" prop="type">
          <el-select
            clearable=""
            v-model="form.type"
            filterable
            placeholder="请选择类型"
            @change="changeType"
          >
            <el-option
              v-for="item in typeList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="告警等级" prop="alarmLevel">
          <el-input
            v-model="form.alarmLevel"
            placeholder="请输入告警等级"
            clearable
            filterable
          />
        </el-form-item>
        <el-form-item
          label="参数合法值"
          prop="legalValue"
          v-if="form.type == 4"
        >
          <el-input
            v-model="form.legalValue"
            placeholder="请输入参数合法值"
            clearable
            filterable
            @change="changelegalValue"
          />
        </el-form-item>

        <el-form-item
          label="参数合法值"
          prop="legalValue"
          v-else-if="form.type == 3"
        >
          <el-select
            clearable=""
            v-model="form.legalValue"
            filterable
            placeholder="请选择合法值"
            @change="changelegalValue"
          >
            <el-option
              v-for="item in booleanList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>

        <div v-else>
          <div
            v-for="(item, index) in legalValueList"
            :key="index"
            style="
              background-color: #eeeeee;
              margin-top: 5px;
              padding: 5px 0px;
              border-radius: 5px;
              width: 100%;
            "
          >
            <div style="margin-top: 5px; margin-left: 10px">
              <span class="el-icon-remove" @click="delItem(item, index)"></span>
            </div>

            <el-form-item label="参数合法值" prop="legalValue">
              <el-select
                style="width: 150px; margin-right: 30px"
                clearable=""
                v-model="legalValueList[index].estimate"
                filterable
                placeholder="操作符"
              >
                <el-option
                  v-for="item in estimateList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
              <el-input
                v-model="legalValueList[index].estimateValue"
                type="double"
                min="0"
                style="width: 100px"
                placeholder="过滤条件值"
              />
            </el-form-item>
          </div>
          <div class="addBtn">
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="addItem"
            >
              新增合法值
            </el-button>
          </div>
        </div>

        <el-form-item label="是否发送通知" prop="isSend">
          <el-select
            clearable=""
            v-model="form.isSend"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in isSendList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="搜索值" prop="searchValue">
                    <el-input v-model="form.searchValue" placeholder="请输入搜索值" clearable filterable
                        @keyup.enter.native="handleQuery" />
                </el-form-item> -->
        <el-form-item label="状态" prop="status">
          <el-select
            clearable=""
            v-model="form.status"
            filterable
            placeholder="请选择"
          >
            <el-option
              v-for="item in statusList"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="editSubmitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listDeviceHeartbeat,
  getDeviceHeartbeatInfo,
  adddeviceHeartbeat,
  updateDeviceHeartbeat,
  deldeviceHeartbeat,
  exportDeviceHeartbeat,
} from "@/api/deviceHeartbeat/index";
import {
  listDeviceHeartbeatDetail,
  getDeviceHeartbeatDetailInfo,
  adddeviceHeartbeatDetail,
  updateDeviceHeartbeatDetail,
  deldeviceHeartbeatDetail,
  exportDeviceHeartbeatDetail,
  updateStatus,
  insertBatchHeartbeat,
} from "@/api/deviceHeartbeat/device-heartbeat-detail";
import {
  listPlatformDeviceHeartbeatPool,
  getPlatformDeviceHeartbeatPool,
  removedPlatformDeviceHeartbeatPool,
  addPlatformDeviceHeartbeatPool,
  updatePlatformDeviceHeartbeatPool,
} from "@/api/deviceHeartbeatPool/index";
import { getProjectList } from "@/api/sku/sku";
export default {
  name: "DeviceHeartbeat",
  data() {
    return {
      //所有项目列表
      projectList: {},
      // 选中记录的数量
      selectionNum: 0,
      //心跳列表
      heartBeatDetailLsit: [],
      heartbeatId: null,
      rebootShell: null,
      projectId: null,
      heartbeat: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        alarmLevel: null,
        heartbeatId: null,
        isSend: null,
        name: null,
        status: null,
        type: null,
        value: null,
        orderByColumn: "id",
        isAsc: "desc",
      },
      // 表单参数
      form: {},
      isSendList: [
        {
          label: "不需要",
          value: "0",
        },
        {
          label: "需要",
          value: "1",
        },
      ],
      typeList: [
        {
          label: "int",
          value: 1,
        },
        {
          label: "double",
          value: 2,
        },
        {
          label: "boolean",
          value: 3,
        },
        {
          label: "string",
          value: 4,
        },
      ],
      statusList: [
        {
          label: "正常",
          value: "0",
        },
        {
          label: "停用",
          value: "1",
        },
      ],
      booleanList: [
        {
          label: "true",
          value: "true",
        },
        {
          label: "false",
          value: "false",
        },
      ],
      //类型为int/double时的参数合法值
      legalValueList: [
        // {
        //   estimate: "=",
        //   estimateValue: "0",
        // },
      ],
      estimateList: [
        {
          label: "等于（=）",
          value: "=",
        },
        {
          label: "不等于（！=）",
          value: "!=",
        },
        {
          label: "大于（>）",
          value: ">",
        },
        {
          label: "小于（<）",
          value: "<",
        },
        {
          label: "大于等于（>=）",
          value: ">=",
        },
        {
          label: "小于等于（<=）",
          value: "<=",
        },
      ],
      rules: {
        alarmLevel: [
          { required: true, message: "告警等级不能为空", trigger: "blur" },
        ],
        name: [{ required: true, message: "名称不能为空", trigger: "blur" }],
        type: [
          { required: true, message: "参数类型不能为空", trigger: "blur" },
        ],
        value: [{ required: true, message: "参数值不能为空", trigger: "blur" }],
      },
      //心跳池列表
      PlatformDeviceHeartbeatPoolList: [],
      poolqueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      poolTotal: 0,
      poolLoading: false,
      chosePool: [],
      editOpen: false,
      editTitle: "",
    };
  },
  created() {
    //this.getProject();
    this.queryParams.heartbeatId =
      this.$route.params && this.$route.params.id.split("&")[0];
    this.heartbeatId =
      this.$route.params && this.$route.params.id.split("&")[0];
    this.heartbeat = this.$route.params && this.$route.params.id.split("&")[1];
    this.rebootShell =
      this.$route.params && this.$route.params.id.split("&")[2];
    this.getList();
  },
  methods: {
    getProject() {
      let params = {
        orderByColumn: "id",
        isAsc: "desc",
      };
      getProjectList(params).then((res) => {
        if (res.code === 200) {
          this.projectList = res.rows;
        }
      });
    },
    //获取心跳池数据
    getpoolList() {
      this.poolLoading = true;
      listPlatformDeviceHeartbeatPool(this.poolqueryParams).then((response) => {
        this.PlatformDeviceHeartbeatPoolList = response.rows;
        this.poolTotal = response.total;
        this.poolLoading = false;
      });
    },
    /** 查询设备心跳 */
    getList() {
      this.loading = true;
      listDeviceHeartbeatDetail(this.queryParams)
        .then((response) => {
          this.heartBeatDetailLsit = response.rows;
          this.total = response.total;
          this.loading = false;
        })
        .catch(() => {
          this.$modal.msgError("获取设备心跳详情失败");
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.editOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        alarmLevel: null,
        heartbeatId: null,
        isSend: null,
        name: null,
        status: null,
        type: null,
        value: null,
        // searchValue: null,
      };
      this.legalValueList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.value);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
      this.selectionNum = selection.length;
    },
    //心跳池选择数据
    // 多选框选中数据
    poolHandleSelectionChange(selection) {
      console.log("selection", selection);
      this.chosePool = selection;
      // this.ids = selection.map((item) => item.id);
      // this.single = selection.length !== 1;
      // this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getpoolList();
      this.form.heartbeatId = this.heartbeatId;
      this.form.alarmLevel = 0;
      this.form.status = "0";
      this.open = true;
      this.title = "添加设备心跳详细信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getDeviceHeartbeatDetailInfo(id).then((response) => {
        this.form = response.data;
        //this.form.type = response.data.type.toString();
        if (response.data.legalValue != null) {
          var list = response.data.legalValue.split(";");
          list.forEach((item, index) => {
            this.legalValueList.push({
              estimateValue: item.replace(/[^0-9]/gi, ""),
              estimate: item.replace(/[0-9]+/g, ""),
            });
          });
        }

        this.editOpen = true;
        this.editTitle = "修改设备心跳详细信息";
      });
    },
    //修改状态
    handleStatusChange(row) {
      const id = row.id || this.ids;
      const params = {
        id: id,
        status: row.status,
      };
      console.log("params", params);

      updateStatus(params)
        .then((response) => {
          this.getList();
          this.$modal.msgSuccess("修改成功");
        })
        .catch((err) => {
          console.log("err", err);

          this.$modal.msgError("状态修改失败");
          this.getList();
        });
    },
    // analydata(list){
    //   list = list.replace("&gt;", ">");
    //   list = list.replace("&lt;", "<");
    //   return list
    // },
    changeType() {
      // this.form.legalValue = "";
    },
    //增加参数合法值规则
    addItem() {
      this.legalValueList.push({
        estimate: "=",
        estimateValue: "0",
      });
      this.changelegalValue();
      this.$forceUpdate();
    },
    //当参数合法值改变的时候默认发送通知
    changelegalValue() {
      this.form.isSend = "1";
    },
    delItem(item, index) {
      // 删除
      this.legalValueList.splice(index, 1);
      console.log("fadsfa", this.legalValueList);

      this.$forceUpdate();
    },
    /** 提交按钮 */
    submitForm() {
      if (this.chosePool.length != 0) {
        const params = this.chosePool.map((item) => {
          item.heartbeatId = this.heartbeatId;
          return item;
        });

        insertBatchHeartbeat(params).then((response) => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      }
    },
    //修改提交表单
    editSubmitForm() {
      if (this.form.type == 1 || this.form.type == 2) {
        if (this.legalValueList.length != 0) {
          this.form.legalValue = "";
          this.legalValueList.forEach((item, index) => {
            if (index != this.legalValueList.length - 1) {
              this.form.legalValue +=
                decodeURI(item.estimate) + item.estimateValue + ";";
            } else {
              this.form.legalValue +=
                decodeURI(item.estimate) + item.estimateValue;
            }
          });
        } else {
          this.form.legalValue = " ";
        }
      }
      this.$refs["form"].validate((valid) => {
        if (valid) {
          updateDeviceHeartbeatDetail(this.form).then((response) => {
            this.$modal.msgSuccess("修改成功");
            this.editOpen = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除心跳编号为"' + ids + '"的数据项？')
        .then(function () {
          // 修改为逻辑删除
          return deldeviceHeartbeatDetail(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch((err) => {
          this.$modal.msgSuccess("删除失败:", err);
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "/genius/platform-device-heartbeat-detail/export",
        {
          ...this.queryParams,
        },
        `product-info_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
